package vip.xiaonuo.modular.xylogy.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.core.annotion.BusinessLog;
import vip.xiaonuo.core.annotion.Permission;
import vip.xiaonuo.core.annotion.version.ApiVersionSwagger;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.enums.LogAnnotionOpTypeEnum;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.modular.xyethnic.service.XyEthnicService;
import vip.xiaonuo.modular.xylogy.entity.XyLogy;
import vip.xiaonuo.modular.xylogy.form.*;
import vip.xiaonuo.modular.xylogy.service.XyLogyService;
import vip.xiaonuo.modular.xylogyauth.entity.XyLogyAuth;
import vip.xiaonuo.modular.xylogyauth.service.XyLogyAuthService;
import vip.xiaonuo.modular.xylogylogs.entity.XyLogyLogs;
import vip.xiaonuo.modular.xylogylogs.param.XyLogyLogsParam;
import vip.xiaonuo.modular.xylogylogs.service.XyLogyLogsService;
import vip.xiaonuo.modular.xylogytemplate.entity.XyLogyTemplate;
import vip.xiaonuo.modular.xylogytemplate.service.XyLogyTemplateService;
import vip.xiaonuo.modular.xyuser.entity.XyUser;
import vip.xiaonuo.modular.xyuser.service.XyUserService;
import vip.xiaonuo.sys.core.msg.Result;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import static vip.xiaonuo.sys.core.msg.ResultUtils.success;

@RestController
@Api(tags = "族谱相关apis")
@ApiVersionSwagger
@RequestMapping("/logy")
public class ApiLogyController
{
    @Autowired
    private XyLogyService xyLogyService;

    @Autowired
    private XyLogyLogsService logyLogsService;

    @Autowired
    private XyEthnicService xyEthnicService;

    @Autowired
    private XyLogyAuthService logyAuthService;


    @PostMapping("/saveLogy")
    @ApiOperation(value = "保存族谱",notes = "templateHost 模板序号,标注当前族谱用的是那个坐标点位\r方便web回显,带id 则修改")
    public synchronized Result createLogy(@RequestBody @Valid LogyForm logyForm){
        xyLogyService.createLogy(logyForm);
        return success();
    }

    @GetMapping("/getById/{id}")
    @ApiOperation(value = "查询族谱详情",notes = "id ")
    public synchronized Result<XyLogy> getById(@PathVariable String id){
        return success( xyLogyService.getById(id));
    }

    @PostMapping("/privateData")
    @ApiOperation("家谱私密设置")
    public Result privateData(@RequestBody @Validated LogyPrivateForm logyPrivateForm){
        xyLogyService.privateData(logyPrivateForm);
        return success();
    }


    @PostMapping("/authLogys")
    @ApiOperation("协作修家谱")
    public Result authLogys(@RequestBody @Validated LogyAuthForm logyAuthForm){
        xyLogyService.authLogys(logyAuthForm);
        return success();
    }

    @PostMapping("/authLogysNew")
    @ApiOperation("协作修家谱新版")
    public Result authLogysNew(@RequestBody @Validated LogyAuthNewForm logyAuthForm){
        xyLogyService.authLogysNew(logyAuthForm);
        return success();
    }

    @PostMapping("/editAuthNew")
    @ApiOperation("编辑协作者新版权限")
    public Result editAuthNew(@RequestBody @Validated LogyEditAuthNewForm logyEditAuthForm){
        xyLogyService.editAuthNew(logyEditAuthForm);
        return success();
    }

    @PostMapping("/editAuth")
    @ApiOperation("编辑协作者权限")
    public Result editAuth(@RequestBody @Validated LogyEditAuthForm logyEditAuthForm){
        xyLogyService.editAuth(logyEditAuthForm);
        return success();
    }

    @GetMapping("/authDel/{id}")
    @ApiOperation("删除协作者")
    public Result authDel(@PathVariable String id){
        XyLogyAuthService xyLogyAuthService = SpringUtil.getBean(XyLogyAuthService.class);
        xyLogyAuthService.removeById(id);
        return success();
    }

    @GetMapping("/authList/{logyId}")
    @ApiOperation("协作人列表")
    public Result<List<XyLogyAuth>> authList(@PathVariable String logyId){
        XyLogyAuthService xyLogyAuthService = SpringUtil.getBean(XyLogyAuthService.class);
        XyUserService xyUserService = SpringUtil.getBean(XyUserService.class);

        List<XyLogyAuth> xyLogyAuths = xyLogyAuthService.list(Wrappers.<XyLogyAuth>lambdaQuery().eq(XyLogyAuth::getLogyId, logyId).orderByDesc(XyLogyAuth::getCreateTime));
        List<XyUser> xyUsers = xyUserService.listByIds(xyLogyAuths.stream().map(XyLogyAuth::getUserId).collect(Collectors.toSet()));
        Map<String, XyUser> xyUserMap = xyUsers.stream().collect(Collectors.toMap(XyUser::getId, Function.identity()));
        return success(xyLogyAuths.stream().map(item -> {
            item.setAuth(item.getAuth());
            item.setAuthNameP(item.getAuthP());
            XyUser xyUser = xyUserMap.get(item.getUserId());
            if (Objects.nonNull(xyUser)){
                item.setHeadImg(xyUser.getImgUrl());
            }
            return item;
        }).collect(Collectors.toList()));
    }


    @PostMapping("/authSearchList")
    @ApiOperation("协作人列表")
    public Result<List<XyLogyAuth>> authSearchList(@RequestBody AuthSearch authSearch){
        XyLogyAuthService xyLogyAuthService = SpringUtil.getBean(XyLogyAuthService.class);
        XyUserService xyUserService = SpringUtil.getBean(XyUserService.class);
        String commName = authSearch.getCommName();

        List<XyLogyAuth> xyLogyAuths = xyLogyAuthService.list(Wrappers.<XyLogyAuth>lambdaQuery().like(StrUtil.isNotBlank(commName),XyLogyAuth::getPhone,commName).or().like(StrUtil.isNotBlank(commName),XyLogyAuth::getAuthName,commName).eq(XyLogyAuth::getLogyId, authSearch.getLogyId()).orderByDesc(XyLogyAuth::getCreateTime));
        Set<String> collect = xyLogyAuths.stream().map(XyLogyAuth::getUserId).collect(Collectors.toSet());
        if (!collect.isEmpty()) {
            List<XyUser> xyUsers = xyUserService.listByIds(collect);
            Map<String, XyUser> xyUserMap = xyUsers.stream().collect(Collectors.toMap(XyUser::getId, Function.identity()));
            return success(xyLogyAuths.stream().map(item -> {
                item.setAuth(item.getAuth());
                item.setAuthNameP(item.getAuthP());
                XyUser xyUser = xyUserMap.get(item.getUserId());
                if (Objects.nonNull(xyUser)){
                    item.setHeadImg(xyUser.getImgUrl());
                }
                return item;
            }).collect(Collectors.toList()));
        }
        return success(Lists.newArrayList());

    }

    /**
     * 当前会员共有多少家谱
     */
    @GetMapping("/thisUserLogy")
    @ApiOperation("当前会员的族谱列表")
    public Result<List<XyLogy>> thisUserLogy(){
        return success(xyEthnicService.thisUserLogy());
    }

    /**
     * 查询操作族谱日志表
     *
     * @author yanwei
     * @date 2023-05-05 15:44:28
     */
    @GetMapping("/xyLogyLogs/page")
    @ApiOperation(value = "操作族谱日志表_查询",notes = "必须传递 logyId")
    public Result<PageResult<XyLogyLogs>> page(XyLogyLogsParam xyLogyLogsParam) {
        PageResult<XyLogyLogs> page = logyLogsService.page(xyLogyLogsParam);
        return success(page);
    }


    /**
     * 获取用户对这个家谱的权限信息
     */
    @GetMapping("/userLogyAuthInfo/{logyId}")
    @ApiOperation("获取用户对这个家谱的权限信息,家谱编号")
    public Result userLogyAuthInfo(@PathVariable    String logyId){
        String userId = LoginContextHolder.me().getSysLoginUser().getStrId();
        List<XyLogyAuth> logyAuthLists = logyAuthService.list(Wrappers.<XyLogyAuth>lambdaQuery().eq(XyLogyAuth::getLogyId,logyId).eq(XyLogyAuth::getUserId, userId));
        if (!logyAuthLists.isEmpty())
        return success(logyAuthLists.get(0).getAuth());

        throw new RuntimeException("暂未权限");
    }



















}
